package com.ruoyi.utils;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 通用工具类
 *
 * @author tanxingxian
 * @date 2022-01-11 14:23
 */
public class CommonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();


    static {
        // 在序列化时日期格式默认为 yyyy-MM-dd HH:mm:ss
        MAPPER.getSerializationConfig().with(DateUtils.DF);
        // 在序列化时忽略值为 null 的属性
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 指定序列化字段顺序
        MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        // 在反序列化时忽略在 json 中存在但 Java 对象不存在的属性
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 格式化输出
        MAPPER.configure(SerializationFeature.INDENT_OUTPUT, true);
        // 忽略无法转换的对象
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }

    /**
     * 将实体类对象转换成json字符串
     */
    public static String serialize(Object object) {

        try {
            if (null != object) {
                return MAPPER.writeValueAsString(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json字符串转换成对应的实体类对象
     */
    public static <T> T deserialize(String json, TypeReference<T> typeReference) {
        try {
            if (StringUtils.isNotBlank(json)) {
                return MAPPER.readValue(json, typeReference);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json字符串转换成对应的实体类对象
     */
    public static <T> T deserialize(String json, Class<T> tClass) {
        try {
            if (StringUtils.isNotBlank(json)) {
                return MAPPER.readValue(json, tClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取随机UUID，使用性能更好的ThreadLocalRandom生成UUID
     *
     * @return 随机UUID
     */
    public static String fastUUID() {
        return UUID.fastUUID().toString();
    }

}
